package edu.ccut.saturn.basecomponent.database.impl.oracle.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.impl.AbstractSQLHandler;
import edu.ccut.saturn.basecomponent.database.preparedstatement.PreparedStatementSetUtils;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;

public class OracleUpdateLOBSQLHandler extends AbstractSQLHandler {

	public List<SaturnData> executeQuery(ISaturnSQL saturnSQL,
			Connection connection) throws SaturnComponentException {
		return null;
	}

	public int executeUpdate(ISaturnSQL saturnSQL, Connection connection)
			throws SaturnComponentException {

		if (connection != null) {
			SaturnData saturnData = saturnSQL.getSaturnData();
			IDataInfo dataInfo = saturnData.getSaturnDataInfo();

			PreparedStatement preparedStatement = null;
			int i = 1;
			try {
				preparedStatement = connection.prepareStatement(saturnSQL
						.getSql());
				debug("UPDATE_SQL = " + saturnSQL.getSql());
				for (String key : dataInfo.keySet()) {
					IDataItem dataItem = dataInfo.getDataItem(key);

					Object value = saturnData.get(key);
					String sqlType = dataItem.getType();
					if (value == null
							|| "true".equalsIgnoreCase(dataItem
									.getIsPrimaryKey())) {
					} else {
						sqlType = getSpecialSqlKey(sqlType);
						if ("NUMBER".equalsIgnoreCase(sqlType)){
							sqlType = dataItem.getJavaType();
						}
						PreparedStatementSetUtils.setValue(sqlType,
								preparedStatement, i++, value);
					}
				}
				super.setConditionPrepareStatement(saturnSQL, i,
						preparedStatement);
				int result = preparedStatement.executeUpdate();
				preparedStatement.clearParameters();
				return result;
			} catch (SQLException e) {
				throw new SaturnComponentException(e);
			} finally {
				if (preparedStatement != null) {
					try {
						preparedStatement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			throw new SaturnComponentException(
					"Can not get Connection in database component");
		}
	}
}